package app.framework.security.jwt;

import app.framework.security.LocalUserDetails;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Maps;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Component
public class JwtUtil implements Serializable {

    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);
    private static final long serialVersionUID = -3301605591108950415L;

    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_USERID = "id";
    private static final String CLAIM_KEY_CREATED = "created";
    private static final String CLAIM_KEY_ROLES = "roles";
    private static final String CLAIM_KEY_EXPIRATION = "expire_seconds";

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    public String getUsernameFromToken(String token) {
        String username = null;
        try {
            final Claims claims = getClaimsFromToken(token);
            if(!isTokenExpired(claims)) {
                username = claims.getSubject();
            }
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    public LocalUserDetails getJwtUserFromToken(String token) {
        final Claims claims = getClaimsFromToken(token);
        if(claims==null || isTokenExpired(token)){
            return null;
        }
        LocalUserDetails user = new LocalUserDetails(
                claims.get(CLAIM_KEY_USERID).toString(),
                claims.getSubject().toString(),
                (List<LinkedHashMap>)claims.get(CLAIM_KEY_ROLES)
        );
        return user;
    }

    public Date getCreatedDateFromToken(String token) {
        Date created;
        try {
            final Claims claims = getClaimsFromToken(token);
            created = new Date((Long) claims.get(CLAIM_KEY_CREATED));
        } catch (Exception e) {
            created = null;
        }
        return created;
    }

    public Date getExpirationDateFromToken(String token) {
        Date expiration;
        try {
            final Claims claims = getClaimsFromToken(token);
            expiration = claims.getExpiration();
        } catch (Exception e) {
            expiration = null;
        }
        return expiration;
    }

    /**
     * JWT缓存对象：减少CPU性能开销
     */
    LoadingCache<String, Claims> tokenCache;

    /**
     * 缓存对象初始化：由于缓存过期时间需要通过配置注入，因此无法静态初始化
     */
    private void initCache(){
        logger.info("初始化token缓存！");
        tokenCache = CacheBuilder.newBuilder()
                .maximumSize(1000)
                .expireAfterWrite(expiration, TimeUnit.SECONDS)
                .build(new CacheLoader<String, Claims>() {
                    @Override
                    public Claims load(String key) {
                        // 这里是key根据实际去取值的方法
//                        logger.info("获取非缓存token:{}",key);
                        return getClaims(key);
                    }
                });
    }

    private Claims getClaims(String token)  {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    private Claims getClaimsFromToken(String token){
//        logger.info("获取缓存token:{}",token);
        if(tokenCache==null) { initCache(); }
        try {
            return  tokenCache.get(token);
        } catch (ExecutionException e) {
            logger.error("token获取失败！", e);
            return null;
        }
    }

    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    private Boolean isTokenExpired(Claims claims) {
        final Date expiration = claims.getExpiration();
        return expiration.before(new Date());
    }

    /**
     * 确保用户修改过默认密码
     * @param created
     * @param lastPasswordReset
     * @return
     */
    private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) {
        return (lastPasswordReset != null && created.before(lastPasswordReset));
    }

    public String generate(LocalUserDetails userDetails) {
        Map<String, Object> claims = Maps.newHashMap();
        claims.put(CLAIM_KEY_USERID, userDetails.getId());
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_ROLES, userDetails.getAuthorities());
        claims.put(CLAIM_KEY_CREATED, new Date());
        claims.put(CLAIM_KEY_EXPIRATION, expiration);
        return generate(claims);
    }

    String generate(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public Boolean canTokenBeRefreshed(String token, Date lastPasswordReset) {
        final Date created = getCreatedDateFromToken(token);
        return !isCreatedBeforeLastPasswordReset(created, lastPasswordReset)
                && !isTokenExpired(token);
    }

    public String refresh(String token) {
        String refreshedToken;
        try {
            final Claims claims = getClaimsFromToken(token);
            claims.put(CLAIM_KEY_CREATED, new Date());
            refreshedToken = generate(claims);
            //新token放入缓存
            tokenCache.put(refreshedToken,claims);
            //原token失效
            tokenCache.invalidate(token);
        } catch (Exception e) {
            logger.error("客户端使用了非法token:{}", token);
            refreshedToken = null;
        }
        return refreshedToken;
    }

//    /**
//     * 简易验证模式：单纯校验token格式
//     * @param token
//     * @return
//     */
//    public Boolean validate(String token) {
//        final Claims claims = getClaimsFromToken(token);
//        return claims!=null? true: false;
//    }

    /**
     * 综合验证模式：强制用户修改初始密码
     * @param token
     * @param userDetails
     * @return
     */
    public Boolean validate(String token, UserDetails userDetails) {
        LocalUserDetails user = (LocalUserDetails) userDetails;
        final String username = getUsernameFromToken(token);
        final Date created = getCreatedDateFromToken(token);
        return (
                username.equals(user.getUsername())
                        && !isTokenExpired(token)
                        && !isCreatedBeforeLastPasswordReset(created, user.getLastPasswordResetDate()));
    }
}

